<!DOCTYPE html>
<html>
<head>
    <title>新建文章</title>
    {% include 'admin/common/header.html' %}
</head>
<body class="pear-container" style="margin-left: 0;">
         <form class="layui-form layui-form-pane" id="acticleform" action="">
    <div id="doc-app">
        <div class="layui-row toolbarrow" >
            <div class="layui-col-md3"></div>
            <div class="toolbar layui-col-md9"></div>
        </div>
        <div class="layui-row">
            <div class="layui-col-md3" style="padding: 5px;">
                <div class="article-left">
                  <div class="layui-card-header">分类</div>
                    <div class="layui-input-block layui-form"  style="margin:10px">
                        <ul id="categoryul"  class="dtree" data-id="0" >
                        </ul>
                    </div>
                 <div class="layui-card-header">属性</div>
                <div class="layui-input-block layui-form"  style="margin:10px">
                <input type="checkbox" name="allsort" value="1"  {% if earticle and earticle.allsort==1 %} checked="checked" {% endif %}  title="头条" lay-skin="primary">
                    <div class="layui-unselect layui-form-checkbox" ><span>头条</span><i class="layui-icon layui-icon-ok"></i></div>
                    <input type="checkbox" name="sort" value="-1" {% if earticle and earticle.sort==-1 %} checked="checked" {% endif %} title="类目置顶" lay-skin="primary">
                    <div class="layui-unselect layui-form-checkbox" ><span>类目置顶</span><i class="layui-icon layui-icon-ok"></i></div>
                     <input type="checkbox" name="lunbo" value="1" title="轮播" {% if earticle and earticle.lunbo==1 %} checked="checked" {% endif %} lay-skin="primary">
                    <div class="layui-unselect layui-form-checkbox" ><span>轮播</span><i class="layui-icon layui-icon-ok"></i></div>
                </div>
                </div>
                </div>
           <div class="layui-col-md9">
             <div class="box">
                 <div style="padding: 10px;">
                    <div class="tit"> <input name="title" id="title" class="layui-input"  placeholder="在此输入标题" value="{% if earticle %}{{ earticle.title }}{% endif %}" multiple="multiple" /></div>
                    <div class="layui-row tit2">
                        <div class="layui-col-md6">
                            <input name="author" class="layui-input"  placeholder="在此输入作者"
                           value="{% if earticle %}{{ earticle.author }}{% endif %}" lay-verify="title" >
                        </div>
                         <div class="layui-col-md6">
                             <input type="text" class="layui-input" value="{% if earticle %}{{ earticle.release_time }}{% endif %}" name="releasetime" id="releasetime"
                           placeholder="yyyy-MM-dd HH:mm:ss" placeholder="发布时间">
                         </div>
                    </div>
                    <div class="doc-cnt" id="remark"></div>
                    <div class="layui-row">
                            <div class="layui-card-header">图片和摘要</div>
                            <div class="layui-btn-container layui-col-md5">
                              <div class="articleupfiles" id="fengmiantu" style="margin-right: 10px;">
                                <i class="layui-icon layui-icon-addition"></i>
                                 <span>封面图({{ coverimgscale }})</span>
                              </div><input name="coverimg" class="layui-input" id="inputcoverimg"  type="hidden" placeholder="请输入" value="{% if earticle %}{{ earticle.coverimg }}{% endif %}" />
                                <div class="articleupfiles" title="点击上传轮播图" id="lunbotu" data-method="setlunboimg" style="width:200px;">
                                    <i class="layui-icon layui-icon-addition"></i>
                                    <span>轮播图非必填{{ lunboimgscale }}</span>
                              </div><input name="lunboimg" class="layui-input" id="inputlunboimg" type="hidden" placeholder="请输入" value="{% if earticle %}{{ earticle.lunboimg }}{% endif %}" />
                            </div>

                            <div class="layui-col-md7">
                                <textarea class="layui-textarea zhiayao" name="literemark" placeholder="在此输入摘要，默认抓取正文前45个字">{% if earticle %}{{ earticle.literemark }}{% endif %}</textarea>
                            </div>
                    </div>
                    <div class="layui-card-header">外部链接</div>
                    <div class="layui-row" style="margin-bottom: 70px;">
                         <input name="linkurl" class="layui-input" style="margin-top: 10px;"  placeholder="如需链接到外部，请输入以 http:// 开头的外部链接非必填" value="{% if earticle %}{{ earticle.linkurl }}{% endif %}" lay-verify="title">
                    </div>
             </div>

            </div>
           </div>
        </div>
    </div>
<div class="article-bottom"  >
    <input name="status" id="status" value="{% if earticle %}{{ earticle.status }}{% else %}0{% endif %}" type="hidden">
    <input name="aid" id="aid" value="{% if earticle %}{{ earticle.id }}{% else %}0{% endif %}" type="hidden">
    <button type="submit" class="pear-btn pear-btn-primary pear-btn-md" style="width: 10%; display: none" id="subbnt" lay-submit="" lay-filter="article-save">
         <i class="layui-icon layui-icon-ok"></i></button>&nbsp;
    <button type="button" class="pear-btn pear-btn-primary pear-btn-md" style="width: 10%" id="savepub" >
         <i class="layui-icon layui-icon-ok"></i>&nbsp;{% if earticle %}修改并发布{% else %}提交并发布{% endif %}</button>&nbsp;
    <button type="button" class="pear-btn pear-btn-primary pear-btn-md" style="width: 10%" id="onlysave" >
         <i class="layui-icon layui-icon-ok"></i>&nbsp;{% if earticle %}仅修改{% else %}仅提交{% endif %}</button>&nbsp;
    <button type="button" class="pear-btn pear-btn-md" id="cancels"><i class="layui-icon layui-icon-close"></i>&nbsp;取消&nbsp;</button>
    &nbsp; &nbsp;
</div>
     </form>
{% include 'admin/common/footer.html' %}
<script>
    var coverimg="{% if earticle %}{{ earticle.coverimg }}{% endif %}";
    var lunboimg="{% if earticle %}{{ earticle.lunboimg }}{% endif %}";
    layui.use(['form', 'jquery', 'tinymce','dropdown','dtree'], function () {
        let form = layui.form
        let $ = layui.jquery
        let laydate = layui.laydate
        let tinymce = layui.tinymce
        let dropdown = layui.dropdown
        let dtree=layui.dtree

        let edit = tinymce.render({
            elem: "#remark",
            height: 400,
            inline:true,
            fixed_toolbar_container:'#doc-app .toolbar',
            custom_ui_selector: 'body',
            content_style: "svg{width:22px;} img{max-width:99%}",
            placeholder:'   在此输入正文',
            auto_focus: true,
            toolbar_mode : 'floating',//floating / sliding / false
            toolbar_sticky: true,
            quickbars_insert_toolbar: '',
            images_upload_url:'/admin/file/mulupload',
            image_advtab: true,
            statusbar:true,

            init_instance_callback: function(editor){$('#doc-app').fadeIn(500);//editor.focus();
                {% if earticle %}
                   editor.setContent('{{ earticle.remark | safe}}');
                     setcoverandlunbo(-1);
                {% endif %}
                },
            setup : function(ed)
            {
                ed.on('init', function()
                {
                    //设置编辑器默认字体和大小
                    this.getDoc().body.style.fontSize = '12';
                    this.getDoc().body.style.fontFamily = 'Arial';
                });
            },
        });

        //日期时间选择器
        laydate.render({elem: '#releasetime', {% if not earticle %} value: new Date(),{% endif %} type: 'datetime'});
        // 树状图菜单
        let cate=dtree.renderSelect({
          elem: '#categoryul',
          initLevel: "4",
          url: '/admin/category/tree',
          method: 'get',
          icon:'4',
          selectInputName: { nodeId: 'categoryid', context: 'categoryname' },
          //skin: 'layui',
          dataFormat: 'list',
          none: "暂时没有分类数据",
          selectTips: "在此选择文章分类",
           // menubar: true, //开启菜单栏
          response: { treeId: 'categoryId', parentId: 'parentId', title: 'categoryName' },
            done: function(result, $ul, first){//只显示文章分类下的所有分类
                //console.log(result,first)
                // 设置第一个分类禁用后搜索显示想显示的总分类
                if(result.data.length>0) {
                    result.data.forEach(function (e) {
                        let childlist = cate.queryListTreeByPid(e.categoryId, result.data);
                        if (childlist.length > 0) {
                            cate.setDisabledNodes(e.categoryId);
                        }
                    });
                    cate.searchNode('文章分类');
                }
                    //cate.dataInit("10");
            }
           {% if earticle %},selectInitVal:"{{ earticle.category_id }}"{% endif %}
        })
        dropdown.render({
          elem: '#fengmiantu'
          ,trigger: 'hover'
          ,data: [{title: '从正文选择',id: 100},{title: '上传封面图',id: 101}]
          ,click: function(obj){
              if(obj.id===101)
              {coverimgopen(0)}else
              {
                  let imglist=getimgsrc(edit.getContent())
                  layer.open({
                  title:obj.title
                  ,type: 1
                  ,fixed: false, maxmin: true
                  ,shadeClose: true
                  ,area:  ['900px', '500px']
                  ,content: '<ul class="file_list" id="imglistul" style="padding: 10px;">'+imglist+' </ul>'
                  ,btn: ['确定', '关闭']
                  ,yes: function(){
                        setcoverandlunbo(0);
                    }
                  ,btn2: function(){
                      layer.closeAll();
                    }
                });
              }
          }
        });

       form.on('submit(article-save)', function (data) {
            data.field.remark=edit.getContent()
           if(data.field.title==="")
            {layer.msg('标题不能为空！',{icon:7,time:1000,anim: 6},function (){$("#title").focus()});return false;}
            if(data.field.remark==="")
            {layer.msg('内容不能为空！',{icon:7,time:1000,anim: 6},function (){edit.focus()});return false;}
            if(data.field.categoryid==="")
            {layer.msg("分类不能为空！", {icon: 7, time: 1000,anim: 6},function (){$("#categoryid_select_input_id").focus()});return false}
            if(!data.field.sort){data.field.sort="0"}//配合文章编辑使用
           //console.log(data.field);return false;
            $.ajax({
                url: '/admin/article/save',
                data: JSON.stringify(data.field),
                dataType: 'json',
                contentType: 'application/json',
                type: 'post',
                success: function (result) {
                    if (result.success) {
                        //top.layui.tab.delTabByElem("content",58)
                        layer.msg(result.msg, {icon: 1, time: 1000}, function () {
                             //关闭当前页
                            parent.layer.close(parent.layer.getFrameIndex(window.name))
                            parent.refresh();
                        })
                    } else {
                        layer.msg(result.msg, {icon: 7, time: 1000,anim:6})
                    }
                }
            })
            return false
        });
        $('#lunbotu').on('click', function(){
           layer.open({
                type: 2,
                title: '上传轮播图',
                shade: 0.1,
                area: ['900px', '500px'],
                content: ['/admin/article/profile?scale={{lunboimgscale}}&coverimg=1&width={{ lunboimgwidth }}&useold=0','no'],
                btn: ['确定', '取消'],
                yes: function (index, layero) {
                  window['layui-layer-iframe' + index].submitForm()
                }
              })
        });
       $('#cancels').on('click', function(){ parent.layer.close(parent.layer.getFrameIndex(window.name)) });
       $('#onlysave').on('click', function(){ $("#status").val(0);$("#subbnt").click() });
        $('#savepub').on('click', function(){ $("#status").val(1); $("#subbnt").click() });
    })

function coverimgopen(useold) {
  layer.open({
        type: 2,
        title: '上传封面图',
        shade: 0.1,
        area: ['900px', '500px'],
        content: ['/admin/article/profile?scale={{coverimgscale}}&coverimg=0&width={{ coverimgwidht }}&useold='+useold,'no'],
        btn: ['确定', '取消'],
        yes: function (index, layero) {
          window['layui-layer-iframe' + index].submitForm()
        }
    })
}
function setcoverandlunbo(models,imgsrc)
{   let setdiv;
    console.log(models,1)
    if(models===0){
        if(imgsrc)
        {coverimg=imgsrc;}
        else{layer.closeAll();coverimgopen(1);}
        setdiv=document.getElementById("fengmiantu");
        setdiv.style.background="url("+coverimg+") no-repeat center center";
        document.getElementById("inputcoverimg").value=coverimg;
        setdiv.style.backgroundSize="100%";
        setdiv.innerHTML="";
    }else if(models===1){
        if(imgsrc)
        {lunboimg=imgsrc;}
        setdiv=document.getElementById("lunbotu");
        setdiv.style.background="url("+lunboimg+") no-repeat center center";
        document.getElementById("inputlunboimg").value=lunboimg;
        setdiv.style.backgroundSize="100%";
        setdiv.innerHTML="";
    }else if(models===-1){
        if(coverimg!=="")
        {
            setdiv=document.getElementById("fengmiantu");
            setdiv.style.background="url("+coverimg+") no-repeat center center";
            setdiv.style.backgroundSize="100%";
            setdiv.innerHTML="";
        }
        if(lunboimg!=="")
        {
            setdiv=document.getElementById("lunbotu");
            setdiv.style.background="url("+lunboimg+") no-repeat center center";
            setdiv.style.backgroundSize="100%";
            setdiv.innerHTML="";
        }
    }
}
function getimgsrc(htmlstr) {
    let reg = /<img.+?src=('|")?([^'"]+)('|")?(?:\s+|>)/gim;
    let imgsrcArr = [];
    while (tem = reg.exec(htmlstr)) {
        imgsrcArr.push(tem[2]);
    }
    console.log(imgsrcArr);
    let imgstr="";
    if(imgsrcArr.length>0) {
        imgsrcArr.forEach(em => {
            imgstr += '<li class="up-no"  >' +
                '<div class="picbox"  lay-data="' + em + '"  onclick="chooseimg(this)">' +
                '<img src="' + em + '" />' +
                '</div></li>';
        })
    }else
    {imgstr="正文中没有图片"}
    return imgstr;
}
//选择图片
 function chooseimg(e) {
     let li=e.parentNode;
     console.log(li);
     let url=e.getAttribute('lay-data');
     if(li.className==="up-no") {
         document.querySelectorAll('#imglistul li').forEach((el,i)=>{el.setAttribute('class','up-no');});
         li.setAttribute('class','up-over');
          coverimg=url;
     }
     else {li.setAttribute('class','up-no');
       coverimg="";
     }
     console.log(coverimg)
}
</script>
</body>
</html>